import logging
import os
from datetime import datetime
from pathlib import Path

import ddddocr
import pytest
from tools.page import page_get

logger = logging.getLogger(__name__)


@pytest.fixture(scope="session", autouse=True)
def page_param():
    logger.info('开始启动浏览器')
    if Path('./已下载文件.pkl').exists():
        Path('./已下载文件.pkl').unlink()
    page = page_get(9230, r'C:\\Chromedata_商品库存')
    yield page
    page.quit()


@pytest.fixture(scope="function", params=[['15867710780', 'yexiong1997']])
def login_聚水潭(request, page_param):
    page = page_param
    page.get("https://www.erp321.com/epaas")
    page.wait(5)
    # 检查是否需要登录
    if page.s_ele('#side'):
        logger.info('登录信息有效,无需登录')
        return
    logger.info('登录信息失效,开始登录')
    page("#login_id").input(request.param[0], clear=True)
    page("#password").input(request.param[1], clear=True)
    page("#agreementCheck").click()
    page('立即登录').click()
    if page('注意：您的密码已经超过3个月未修改(304)，请您尽快修改密码！', timeout=3):
        page('确认').click()
    logger.info('登录成功')


# 识别验证码
def get_captcha(screenshot_path):
    ocr = ddddocr.DdddOcr()
    with open(screenshot_path, 'rb') as f:
        img_bytes = f.read()
    result = ocr.classification(img_bytes)
    return result


@pytest.fixture(scope="function", params=[['zhanhuawei', 'weiwei666']])
def login_ERP(request, page_param):
    page = page_param
    page.get("http://192.168.16.240:8001/rebotlogin")
    logger.info('开始登录')
    page('@placeholder=请输入账号').input(request.param[0])
    page('@placeholder=请输入密码').input(request.param[1])
    os.remove('./imgs/imgs.png')
    page("t:img").save(r".\imgs", name='imgs.png')
    result = get_captcha(r".\imgs\imgs.png")
    page('@placeholder=验证码').input(result)
    page(".el-button el-button--primary el-button--mini is-round").click()
    logger.info('登录成功')


@pytest.fixture(scope="session", autouse=True, name='timestamp')
def get_timestamp():
    timestamp = datetime.now().strftime('%Y%m%d%H%M')
    yield timestamp
